package com.example.spider.schedule;

import lombok.extern.slf4j.Slf4j;
import org.shoulder.batch.progress.BatchProgressCache;
import org.shoulder.batch.progress.BatchProgressRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 进度自动清理相关
 *
 * @author lym
 */
@Slf4j
@Order()
@Component
public class ProgressCacheAutoCleanScheduled {

    private static final Duration EXPIRE_DURATION = Duration.ofDays(1);
    @Autowired
    private BatchProgressCache progressCache;

    /**
     * 定时清理今天以前已经完成的
     */
    @Scheduled(cron = "0 0 */2 * * ?")
    public void starSpider() {
        progressCache.getAllTaskProgress().forEach((id, progress) -> {
            BatchProgressRecord record = progress.getBatchProgress();
            if (record.hasFinish() && Duration.between(record.getStopTime(), LocalDateTime.now()).compareTo(EXPIRE_DURATION) > 0) {
                progressCache.evict(id);
            }
        });
    }

}
